package com.scm.web.controller.order;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.scm.common.config.ReptilemanagerConfig;
import com.scm.common.config.ServerConfig;
import com.scm.common.core.domain.entity.SysUser;
import com.scm.common.enums.OrderTypeEnum;
import com.scm.common.utils.file.FileUploadUtils;
import com.scm.common.utils.file.FileUtils;
import com.scm.dto.req.order.OrderImportBean;
import com.scm.common.core.page.PageDomain;
import com.scm.common.core.page.TableSupport;
import com.scm.common.utils.TOTransferHelper;
import com.scm.dto.req.order.OrderZhipaiReq;
import com.scm.dto.resp.order.*;
import com.scm.dto.resp.product.ProductSyncStatus;
import com.scm.manager.OrderManager;
import com.scm.persist.model.ScmOrder;
import com.scm.persist.model.ScmOrderLog;
import com.scm.persist.model.ScmOrderOperation;
import com.scm.persist.model.ScmOrderProduct;
import com.scm.service.IScmOrderOperationService;
import com.scm.service.IScmOrderService;
import com.scm.system.service.ISysUserService;
import org.apache.commons.compress.utils.Lists;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.scm.common.annotation.Log;
import com.scm.common.enums.BusinessType;
import com.scm.common.core.controller.BaseController;
import com.scm.common.core.domain.AjaxResult;
import com.scm.common.utils.poi.ExcelUtil;
import com.scm.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 订单主Controller
 *
 * @author reptilemanager
 * @date 2024-02-08
 */
@Controller
@RequestMapping("/scm/order")
public class ScmOrderController extends BaseController
{
    private String prefix = "order";

    @Autowired
    private IScmOrderService scmOrderService;

    @Autowired
    private IScmOrderOperationService scmOrderOperationService;

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ServerConfig serverConfig;




    @RequiresPermissions("order:view")
    @GetMapping()
    public String order()
    {

        return prefix + "/order";
    }

    /**
     * 查询订单主列表
     */
    @RequiresPermissions("order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ScmOrder scmOrder)
    {

        //当前登陆用户
        SysUser sysUser = getSysUser();

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer start = (pageDomain.getPageNum() - 1) * 10;

        QueryOrderPageResp resp = scmOrderService.selectScmOrderList(scmOrder,start,pageDomain.getPageSize(),getSysUser());
        return getDataTable(resp.getList());
    }

    /**
     * 查询订单商品信息
     */
    @RequiresPermissions("order:list")
    @PostMapping("/product/list")
    @ResponseBody
    public TableDataInfo productList(@RequestParam("orderId") Long orderId)
    {

        //当前登陆用户
        SysUser sysUser = getSysUser();
        List<OrderProductDo> list = scmOrderService.selectScmOrderProductList(sysUser.getTenantId(),orderId);
        return getDataTable(list);
    }

    /**
     * 查询订单操作记录
     */
    @RequiresPermissions("order:list")
    @PostMapping("/log/list")
    @ResponseBody
    public TableDataInfo logList(@RequestParam("orderId") Long orderId)
    {
        //当前登陆用户
        SysUser sysUser = getSysUser();
        List<ScmOrderLogDO> list = scmOrderService.selectScmOrderLogList(sysUser.getTenantId(),orderId);
        return getDataTable(list);
    }


    @GetMapping("/detail/{scmOrderId}")
    public String detail(@PathVariable("scmOrderId") Long scmOrderId, ModelMap mmap)
    {

        OrderDetailDo orderDetailDo = orderManager.getOrderDetailById(scmOrderId);
        mmap.put("order", orderDetailDo);

        return prefix + "/detail";
    }


    /**
     * 导出订单主列表
     */
    @RequiresPermissions("order:export")
    @Log(title = "订单主", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ScmOrder scmOrder)
    {
        QueryOrderPageResp resp = scmOrderService.selectScmOrderList(scmOrder,0,10,getSysUser());
        ExcelUtil<OrderPageDo> util = new ExcelUtil<OrderPageDo>(OrderPageDo.class);
        return util.exportExcel(resp.getList(), "订单主数据");
    }

    @RequiresPermissions("order:export")
    @Log(title = "订单主", businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate(ScmOrder scmOrder)
    {
        //QueryOrderPageResp resp = scmOrderService.selectScmOrderList(scmOrder,0,10,getSysUser());
        ExcelUtil<OrderImportVO> util = new ExcelUtil<OrderImportVO>(OrderImportVO.class);
        return util.exportExcel(new ArrayList<>(), "订单主数据");
    }

    private List<OrderImportVO> converterOrderImportVOByOrderPageDo(List<OrderPageDo> orderPageDoList) {
        List<OrderImportVO> orderImportVOList = Lists.newArrayList();
        if(CollectionUtils.isEmpty(orderPageDoList)){
            return orderImportVOList;
        }
        orderPageDoList.forEach(orderPageDo -> {
            OrderImportVO orderImportVO = TOTransferHelper.trans2TO(orderPageDo, OrderImportVO.class);
            orderImportVOList.add(orderImportVO);
        });
        return orderImportVOList;
    }

    /**
     * 导入数据
     */
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        //当前登陆用户
        SysUser sysUser = getSysUser();

        ExcelUtil<OrderImportVO> util = new ExcelUtil<OrderImportVO>(OrderImportVO.class);
        List<OrderImportVO> orderImportModelList = util.importExcel(file.getInputStream());

        List<OrderImportBean> orderImportBeanList =converterOrderImportBeanByVO(orderImportModelList);
        orderManager.importOmsOrder(sysUser,orderImportBeanList);

        String message = "";  //importUser(userList, updateSupport);
        return AjaxResult.success(message);
    }


    private List<OrderImportBean> converterOrderImportBeanByVO( List<OrderImportVO> orderImportModelList ){

        List<OrderImportBean> orderImportBeanList = Lists.newArrayList();

        if(CollectionUtils.isEmpty(orderImportModelList)){
            return orderImportBeanList;
        }

        for (OrderImportVO orderImportVO : orderImportModelList) {

            OrderImportBean orderImportBean = TOTransferHelper.trans2TO(orderImportVO,OrderImportBean.class);
            orderImportBean.setRemark(orderImportVO.getExcelRemark());
            orderImportBeanList.add(orderImportBean);

        }

        return orderImportBeanList;

    }
    /**
     * 新增订单主
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }


    /**
     * 报备订单，代理商可以报备订单，表示该订单是自己的，提示渠道商分配订单给代理商
     */
    @GetMapping("/baobei")
    public String baobei()
    {
        return prefix + "/baobei";
    }


    @PostMapping( "/submitBaobei")
    @ResponseBody
    public AjaxResult submitBaobei(OrderBaobeiVO orderBaobeiVO)
    {
        SysUser sysUser = getSysUser();

        orderManager.saveBaobei(orderBaobeiVO.getOmsOrderId(),sysUser);
        return toAjax(1);
    }


    /**
     * 指派订单，渠道商商可以指派订单给代理商
     */
    @GetMapping("/zhipai/{id}")
    public String zhipai(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysUser sysUser = getSysUser();

        QueryOrderZhipairenResp resp = orderManager.queryOrderZhipairen(id,sysUser);

        //查找报备该订单的人员

        mmap.put("scmOrder", resp.getScmOrder());
        mmap.put("waitZhipaiList", resp.getList());

        return prefix + "/zhipai";
    }




    @PostMapping( "/submitZhipai")
    @ResponseBody
    public AjaxResult submitZhipai(OrderZhipaiVO orderZhipaiVO)
    {

        //当前登陆用户
        SysUser sysUser = getSysUser();

        scmOrderOperationService.zhipaiOrder(OrderZhipaiReq.builder().orderId(orderZhipaiVO.getId()).zhipaiUserId(orderZhipaiVO.getUserId()).zhipaiOperator(sysUser.getUserId()).build(),sysUser);
        return toAjax(1);
    }


    /**
     * 新增保存订单主
     */
    @RequiresPermissions("order:add")
    @Log(title = "订单主", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ScmOrder scmOrder)
    {
        SysUser sysUser = getSysUser();

        scmOrderService.insertScmOrder(scmOrder,sysUser);
        return toAjax(1);
    }

    /**
     * 修改订单主
     */
    @RequiresPermissions("order:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysUser sysUser = getSysUser();

        ScmOrder scmOrder = scmOrderService.selectScmOrderById(id);
        mmap.put("scmOrder", scmOrder);
        return prefix + "/edit";
    }

    /**
     * Oms爬虫同步订单商品信息
     */
    @RequiresPermissions("order:edit")
    @PostMapping("/syncProudct/{id}")
    @ResponseBody
    public AjaxResult syncProudct(@PathVariable("id") Long id, ModelMap mmap)
    {
        SysUser sysUser = getSysUser();

        List<ProductSyncStatus> list = orderManager.syncScmOrderProduct(sysUser,id);

        return AjaxResult.success(list);
    }


    /**
     * 修改保存订单主
     */
    @RequiresPermissions("order:edit")
    @Log(title = "订单主", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ScmOrder scmOrder)
    {
        SysUser sysUser = getSysUser();

        return toAjax(orderManager.updateScmOrder(sysUser,scmOrder));
    }

    /**
     * 删除订单主
     */
    @RequiresPermissions("order:remove")
    @Log(title = "订单主", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {


        return toAjax(scmOrderService.deleteScmOrderById(0l));
    }

    @GetMapping("/uploadWaitReceipt/{id}")
    public String uploadWaitReceipt(@PathVariable("id") Long id, ModelMap mmap)
    {

        ScmOrderOperation scmOrderOperation = scmOrderService.selectByScmOrderId(id);
        mmap.put("scmOrder", scmOrderOperation);
        List<OrderTypeEnum> enumList = Arrays.stream(OrderTypeEnum.values()).collect(Collectors.toList());
        mmap.put("OrderTypes", enumList);

        return prefix + "/upload_wait_receipt";
    }



    /**
     * 上传待签收单
     * @param waitReceiptFile
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadWaitReceipt")
    @ResponseBody
    public AjaxResult uploadWaitReceipt(MultipartFile waitReceiptFile,Long id,String orderType) throws Exception
    {
        if(id == null){
            // todo 异常
            logger.error("id error");
            return AjaxResult.error("系统异常");
        }
        try
        {
            // 上传文件路径
            String filePath = ReptilemanagerConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, waitReceiptFile);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", waitReceiptFile.getOriginalFilename());
            SysUser sysUser = getSysUser();
            orderManager.uploadWaitReceipt(id,sysUser,url,orderType);
            return ajax;
        }
        catch (Exception e)
        {
            logger.error("上传文件异常",e);
            return AjaxResult.error(e.getMessage());
        }


    }

    /**
     * 上传发票
     * @param waitReceiptFile
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadInvoice")
    @ResponseBody
    public AjaxResult uploadInvoice(MultipartFile waitReceiptFile,Long id,String orderType) throws Exception
    {
        if(id == null){
            // todo 异常
            logger.error("id error");
            return AjaxResult.error("系统异常");
        }
        try
        {
            // 上传文件路径
            String filePath = ReptilemanagerConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, waitReceiptFile);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", waitReceiptFile.getOriginalFilename());
            SysUser sysUser = getSysUser();
            orderManager.uploaduploadInvoice(id,sysUser,url,orderType);
            return ajax;
        }
        catch (Exception e)
        {
            logger.error("上传文件异常",e);
            return AjaxResult.error(e.getMessage());
        }


    }
    @GetMapping("/uploadInvoice/{id}")
    public String uploadInvoice(@PathVariable("id") Long id, ModelMap mmap)
    {

        ScmOrderOperation scmOrderOperation = scmOrderService.selectByScmOrderId(id);
        mmap.put("scmOrder", scmOrderOperation);
        List<OrderTypeEnum> enumList = Arrays.stream(OrderTypeEnum.values()).collect(Collectors.toList());
        mmap.put("OrderTypes", enumList);

        return prefix + "/upload_invoice";
    }


    /**
     * 上传订单
     * @param receipt_file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadCredentials")
    @ResponseBody
    public AjaxResult uploadCredentials(MultipartFile receipt_file,Long id) throws Exception
    {
        if(id == null){
            // todo 异常
            return AjaxResult.error("系统异常");
        }
        try
        {
            // 上传文件路径
            String filePath = ReptilemanagerConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, receipt_file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", receipt_file.getOriginalFilename());
            SysUser sysUser = getSysUser();
            orderManager.uploadCredentials(id,sysUser,url);
            return ajax;
        }
        catch (Exception e)
        {
            logger.error("上传文件异常",e);
            return AjaxResult.error(e.getMessage());
        }

    }

    @GetMapping("/uploadReceipt/{id}")
    public String uploadReceipt(@PathVariable("id") Long id, ModelMap mmap)
    {

        ScmOrderOperation scmOrderOperation = scmOrderService.selectByScmOrderId(id);

        mmap.put("scmOrder", scmOrderOperation);


        return prefix + "/uploadReceipt";
    }

    @RequiresPermissions("order:view")
    @GetMapping("/outInventory/{id}")
    public String outInventory()
    {
        //出库 //验证出库逻辑



        return  "inventory/out/order";
    }


}
